{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 9.24 \u89e3\u6790\u4e0e\u5206\u6790Python\u6e90\u7801\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u95ee\u9898\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f60\u60f3\u5199\u89e3\u6790\u5e76\u5206\u6790Python\u6e90\u4ee3\u7801\u7684\u7a0b\u5e8f\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u89e3\u51b3\u65b9\u6848\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5927\u90e8\u5206\u7a0b\u5e8f\u5458\u77e5\u9053Python\u80fd\u591f\u8ba1\u7b97\u6216\u6267\u884c\u5b57\u7b26\u4e32\u5f62\u5f0f\u7684\u6e90\u4ee3\u7801\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "x = 42\neval('2 + 3*4 + x')"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "exec('for i in range(10): print(i)')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5c3d\u7ba1\u5982\u6b64\uff0cast \u6a21\u5757\u80fd\u88ab\u7528\u6765\u5c06Python\u6e90\u7801\u7f16\u8bd1\u6210\u4e00\u4e2a\u53ef\u88ab\u5206\u6790\u7684\u62bd\u8c61\u8bed\u6cd5\u6811\uff08AST\uff09\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import ast\nex = ast.parse('2 + 3*4 + x', mode='eval')\nex"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "ast.dump(ex)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "top = ast.parse('for i in range(10): print(i)', mode='exec')\ntop"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "ast.dump(top)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5206\u6790\u6e90\u7801\u6811\u9700\u8981\u4f60\u81ea\u5df1\u66f4\u591a\u7684\u5b66\u4e60\uff0c\u5b83\u662f\u7531\u4e00\u7cfb\u5217AST\u8282\u70b9\u7ec4\u6210\u7684\u3002\n\u5206\u6790\u8fd9\u4e9b\u8282\u70b9\u6700\u7b80\u5355\u7684\u65b9\u6cd5\u5c31\u662f\u5b9a\u4e49\u4e00\u4e2a\u8bbf\u95ee\u8005\u7c7b\uff0c\u5b9e\u73b0\u5f88\u591a visit_NodeName() \u65b9\u6cd5\uff0c\nNodeName() \u5339\u914d\u90a3\u4e9b\u4f60\u611f\u5174\u8da3\u7684\u8282\u70b9\u3002\u4e0b\u9762\u662f\u8fd9\u6837\u4e00\u4e2a\u7c7b\uff0c\u8bb0\u5f55\u4e86\u54ea\u4e9b\u540d\u5b57\u88ab\u52a0\u8f7d\u3001\u5b58\u50a8\u548c\u5220\u9664\u7684\u4fe1\u606f\u3002"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import ast\n\nclass CodeAnalyzer(ast.NodeVisitor):\n    def __init__(self):\n        self.loaded = set()\n        self.stored = set()\n        self.deleted = set()\n\n    def visit_Name(self, node):\n        if isinstance(node.ctx, ast.Load):\n            self.loaded.add(node.id)\n        elif isinstance(node.ctx, ast.Store):\n            self.stored.add(node.id)\n        elif isinstance(node.ctx, ast.Del):\n            self.deleted.add(node.id)\n\n# Sample usage\nif __name__ == '__main__':\n    # Some Python code\n    code = '''\n    for i in range(10):\n        print(i)\n    del i\n    '''\n\n    # Parse into an AST\n    top = ast.parse(code, mode='exec')\n\n    # Feed the AST to analyze name usage\n    c = CodeAnalyzer()\n    c.visit(top)\n    print('Loaded:', c.loaded)\n    print('Stored:', c.stored)\n    print('Deleted:', c.deleted)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5982\u679c\u4f60\u8fd0\u884c\u8fd9\u4e2a\u7a0b\u5e8f\uff0c\u4f60\u4f1a\u5f97\u5230\u4e0b\u9762\u8fd9\u6837\u7684\u8f93\u51fa\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "Loaded: {'i', 'range', 'print'}\nStored: {'i'}\nDeleted: {'i'}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u6700\u540e\uff0cAST\u53ef\u4ee5\u901a\u8fc7 compile() \u51fd\u6570\u6765\u7f16\u8bd1\u5e76\u6267\u884c\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "exec(compile(top,'<stdin>', 'exec'))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u8ba8\u8bba\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5f53\u4f60\u80fd\u591f\u5206\u6790\u6e90\u4ee3\u7801\u5e76\u4ece\u4e2d\u83b7\u53d6\u4fe1\u606f\u7684\u65f6\u5019\uff0c\u4f60\u5c31\u80fd\u5199\u5f88\u591a\u4ee3\u7801\u5206\u6790\u3001\u4f18\u5316\u6216\u9a8c\u8bc1\u5de5\u5177\u4e86\u3002\n\u4f8b\u5982\uff0c\u76f8\u6bd4\u76f2\u76ee\u7684\u4f20\u9012\u4e00\u4e9b\u4ee3\u7801\u7247\u6bb5\u5230\u7c7b\u4f3c exec() \u51fd\u6570\u4e2d\uff0c\u4f60\u53ef\u4ee5\u5148\u5c06\u5b83\u8f6c\u6362\u6210\u4e00\u4e2aAST\uff0c\n\u7136\u540e\u89c2\u5bdf\u5b83\u7684\u7ec6\u8282\u770b\u5b83\u5230\u5e95\u662f\u600e\u6837\u505a\u7684\u3002\n\u4f60\u8fd8\u53ef\u4ee5\u5199\u4e00\u4e9b\u5de5\u5177\u6765\u67e5\u770b\u67d0\u4e2a\u6a21\u5757\u7684\u5168\u90e8\u6e90\u7801\uff0c\u5e76\u4e14\u5728\u6b64\u57fa\u7840\u4e0a\u6267\u884c\u67d0\u4e9b\u9759\u6001\u5206\u6790\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u9700\u8981\u6ce8\u610f\u7684\u662f\uff0c\u5982\u679c\u4f60\u77e5\u9053\u81ea\u5df1\u5728\u5e72\u5565\uff0c\u4f60\u8fd8\u80fd\u591f\u91cd\u5199AST\u6765\u8868\u793a\u65b0\u7684\u4ee3\u7801\u3002\n\u4e0b\u9762\u662f\u4e00\u4e2a\u88c5\u9970\u5668\u4f8b\u5b50\uff0c\u53ef\u4ee5\u901a\u8fc7\u91cd\u65b0\u89e3\u6790\u51fd\u6570\u4f53\u6e90\u7801\u3001\n\u91cd\u5199AST\u5e76\u91cd\u65b0\u521b\u5efa\u51fd\u6570\u4ee3\u7801\u5bf9\u8c61\u6765\u5c06\u5168\u5c40\u8bbf\u95ee\u53d8\u91cf\u964d\u4e3a\u51fd\u6570\u4f53\u4f5c\u7528\u8303\u56f4\uff0c"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# namelower.py\nimport ast\nimport inspect\n\n# Node visitor that lowers globally accessed names into\n# the function body as local variables.\nclass NameLower(ast.NodeVisitor):\n    def __init__(self, lowered_names):\n        self.lowered_names = lowered_names\n\n    def visit_FunctionDef(self, node):\n        # Compile some assignments to lower the constants\n        code = '__globals = globals()\\n'\n        code += '\\n'.join(\"{0} = __globals['{0}']\".format(name)\n                            for name in self.lowered_names)\n        code_ast = ast.parse(code, mode='exec')\n\n        # Inject new statements into the function body\n        node.body[:0] = code_ast.body\n\n        # Save the function object\n        self.func = node\n\n# Decorator that turns global names into locals\ndef lower_names(*namelist):\n    def lower(func):\n        srclines = inspect.getsource(func).splitlines()\n        # Skip source lines prior to the @lower_names decorator\n        for n, line in enumerate(srclines):\n            if '@lower_names' in line:\n                break\n\n        src = '\\n'.join(srclines[n+1:])\n        # Hack to deal with indented code\n        if src.startswith((' ','\\t')):\n            src = 'if 1:\\n' + src\n        top = ast.parse(src, mode='exec')\n\n        # Transform the AST\n        cl = NameLower(namelist)\n        cl.visit(top)\n\n        # Execute the modified AST\n        temp = {}\n        exec(compile(top,'','exec'), temp, temp)\n\n        # Pull out the modified code object\n        func.__code__ = temp[func.__name__].__code__\n        return func\n    return lower"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4e3a\u4e86\u4f7f\u7528\u8fd9\u4e2a\u4ee3\u7801\uff0c\u4f60\u53ef\u4ee5\u50cf\u4e0b\u9762\u8fd9\u6837\u5199\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "INCR = 1\n@lower_names('INCR')\ndef countdown(n):\n    while n > 0:\n        n -= INCR"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u88c5\u9970\u5668\u4f1a\u5c06 countdown() \u51fd\u6570\u91cd\u5199\u4e3a\u7c7b\u4f3c\u4e0b\u9762\u8fd9\u6837\u5b50\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def countdown(n):\n    __globals = globals()\n    INCR = __globals['INCR']\n    while n > 0:\n        n -= INCR"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5728\u6027\u80fd\u6d4b\u8bd5\u4e2d\uff0c\u5b83\u4f1a\u8ba9\u51fd\u6570\u8fd0\u884c\u5feb20%"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u73b0\u5728\uff0c\u4f60\u662f\u4e0d\u662f\u60f3\u4e3a\u4f60\u6240\u6709\u7684\u51fd\u6570\u90fd\u52a0\u4e0a\u8fd9\u4e2a\u88c5\u9970\u5668\u5462\uff1f\u6216\u8bb8\u4e0d\u4f1a\u3002\n\u4f46\u662f\uff0c\u8fd9\u5374\u662f\u5bf9\u4e8e\u4e00\u4e9b\u9ad8\u7ea7\u6280\u672f\u6bd4\u5982AST\u64cd\u4f5c\u3001\u6e90\u7801\u64cd\u4f5c\u7b49\u7b49\u7684\u4e00\u4e2a\u5f88\u597d\u7684\u6f14\u793a\u8bf4\u660e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u672c\u8282\u53d7\u53e6\u5916\u4e00\u4e2a\u5728 ActiveState \u4e2d\u5904\u7406Python\u5b57\u8282\u7801\u7684\u7ae0\u8282\u7684\u542f\u793a\u3002\n\u4f7f\u7528AST\u662f\u4e00\u4e2a\u66f4\u52a0\u9ad8\u7ea7\u70b9\u7684\u6280\u672f\uff0c\u5e76\u4e14\u4e5f\u66f4\u7b80\u5355\u4e9b\u3002\u53c2\u8003\u4e0b\u9762\u4e00\u8282\u83b7\u5f97\u5b57\u8282\u7801\u7684\u66f4\u591a\u4fe1\u606f\u3002"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": true,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}